package com.eshop.logging.tools.controller;

import org.springframework.web.bind.annotation.PostMapping;
import com.eshop.annotation.AnonymousAccess;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.eshop.exception.BadRequestException;
import com.eshop.utils.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import com.eshop.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SmsApiController
{
    @Autowired
    private RestTemplate restTemplate;
    @Value("${product.url}")
    private String url;
    @Autowired
    private RedisUtils redisUtils;
    
    @AnonymousAccess
    @PostMapping({ "/api/sendSMS" })
    public ResponseEntity<Object> code(@RequestBody final ApplyParam applyParam) throws Exception {
        final String verifyCode = (String)this.redisUtils.get(applyParam.getUuid());
        this.redisUtils.del(new String[] { applyParam.getUuid() });
        if (StringUtils.isBlank((CharSequence)verifyCode)) {
            throw new BadRequestException("图形验证码不存在或已过期");
        }
        if (StringUtils.isBlank((CharSequence)applyParam.getCode()) || !applyParam.getCode().equalsIgnoreCase(verifyCode)) {
            throw new BadRequestException("页面中图形验证码输入错误");
        }
        if (StringUtils.isBlank((CharSequence)applyParam.getMobilePhone())) {
            throw new BadRequestException("请输入手机号");
        }
        String code = (String)this.redisUtils.get(applyParam.getMobilePhone());
        if (StrUtil.isNotEmpty((CharSequence)code)) {
            throw new BadRequestException("验证码已发送,请不要重复请求");
        }
        code = RandomUtil.randomNumbers(6);
        final Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("code", code);
        final ResponseEntity<String> result = (ResponseEntity<String>)this.restTemplate.postForEntity(this.url + "/sendSMS/" + applyParam.getMobilePhone(), (Object)map, (Class)String.class, new Object[0]);
        final HashMap resultMap = JsonUtil.fromJson((String)result.getBody(), HashMap.class);
        if ("OK".equals(resultMap.get("code"))) {
            this.redisUtils.set(applyParam.getMobilePhone(), (Object)code, 120L, TimeUnit.SECONDS);
            return (ResponseEntity<Object>)ResponseEntity.ok((Object)resultMap);
        }
        throw new BadRequestException((String)resultMap.get("message"));
    }
}
